package com.mall.common.util;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.remoting.caucho.HessianServiceExporter;

import sun.misc.BASE64Decoder;

/**  
 * @author lhy
 * @version datetime：2014年8月30日 下午4:11:39   
 */
public class HouseHessianServiceExporter  extends HessianServiceExporter {

    private static Log log = LogFactory.getLog("HouseHessian"); 
    
	private String[] entryIP = { "127.0.0.1", "192.168.0.8", "192.168.0.7" };
    
    private static final String HESSIAN_NAME_VALIDATE = "bangke@123";
    private static final String HESSIAN_PASSWORD_VALIDATE = "bangke@456";
    
    @Override
    public void handleRequest(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { 
    	HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
    	String authorization = req.getHeader("authorization");
    	/**
    	 * IP地址验证 TODO
    	 */
        if(validataIp(IpUtil.getIpAddr(request))){
            log.info("call ==>remote 's IP:"+IpUtil.getIpAddr(request)+"remote 's host: "+request.getRemoteHost());
            super.handleRequest(request, response);
        }else if (validataUserAndPass(authorization)) {
        	super.handleRequest(request, response);
        }else{
        	resp.setStatus(403);
        }
    }
    
    public Boolean validataIp(String ipFrom) {
		log.info("try ==>remote 's IP:" + ipFrom);
		int call = 0;
		for (String ip : entryIP) {
			if (ip.equals(ipFrom)) {
				call++;
			}
		}
		if(call > 0){
			return true;
		}
		return false;
	}
    
    /**
	 * IP地址验证 用户名验证
	 */
    public Boolean validataUserAndPass(String authorization) throws IOException {
		log.info("try ==>authorization:" + authorization);
		if ((authorization == null) || authorization.equals("")) {
			return false;
		}
		String userAndPass = new String(new BASE64Decoder().decodeBuffer(authorization.split(" ")[1]));
		if (userAndPass.split(":").length < 2) {
			return false;
		}
		String user = userAndPass.split(":")[0];
		String pass = userAndPass.split(":")[1];
		if ((pass != null) && (user != null) && user.equalsIgnoreCase(HESSIAN_NAME_VALIDATE) && pass.equalsIgnoreCase(HESSIAN_PASSWORD_VALIDATE)) {
			return true;
		}
		return false;
	}
}
